library(survey)
library(dplyr)
library(ggplot2)
library(gridExtra)

# Figure 9.5
summary(factor(df$Q5D))
summary(factor(df$Q5F))
df2 <- df[df$Q11<5,]

df2$Q11T <- NA
df2$Q11T[df2$Q11>2] <- 0
df2$Q11T[df2$Q11<3] <- 1

# Important
df2$Q5D[df2$Q5D>3] <- NA
df2$Q5D[df2$Q5D==3] <- 0
df2$Q5D[df2$Q5D==2] <- 0.5
df2$Q5D[df2$Q5D==1] <- 1

df2$Q5F[df2$Q5F>3] <- NA
df2$Q5F[df2$Q5F==3] <- 0
df2$Q5F[df2$Q5F==2] <- 0.5
df2$Q5F[df2$Q5F==1] <- 1

df2 <- df2[df2$P_ASSIGN1==1,]

w2_design <-
  svydesign(
    id = ~ 1,
    weights = ~ weight2,
    data = df2
  )

f.5D <- svyby(~ Q5D, ~Q11T+party, w2_design, svymean, na.rm = TRUE)
f.5F <- svyby(~ Q5F, ~Q11T+party, w2_design, svymean, na.rm = TRUE)

# Humanitarian Missions
g.5D <- ggplot(f.5D, aes(x=factor(party),y=Q5D,fill=factor(Q11T),label=round(Q5D,digits=2)))+
  geom_col(position = position_dodge(), width=0.5)+
  geom_text(size=3,position=position_dodge(1),vjust=-.5)+
  ylim(0,1)+
  theme(legend.position = "null")+
  scale_x_discrete(labels=c("Democrat",'Independent',"Republican"))+
  xlab("")+
  ylab("Importance of Humanitarian Missions Abroad\n")

# Civil War
g.5F <- ggplot(f.5F, aes(x=factor(party),y=Q5F,fill=factor(Q11T),label=round(Q5F,digits=2)))+
  geom_col(position = position_dodge(), width=0.5)+
  geom_text(size=3,position=position_dodge(1),vjust=-.5)+
  ylim(0,1)+
  theme(legend.position = "null")+
  scale_x_discrete(labels=c("Democrat",'Independent',"Republican"))+
  xlab("")+
  ylab("Importance of Civil War Intervention Missions\n")

grid.arrange(g.5D,g.5F,ncol=2)
